var base = require("mlib/comp/base"); // 基础对象
var parseModule = require("mlib/dom/parseModule"); // 页面模块自动解析

var touch = require("mlib/evt/touch");
var closest = require("mlib/dom/closest");
var ajax = require("mlib/io/ajax");
var extend = require("../util/mix");
var Alert = require("pages/layer/weuialert");
var showMessage = require("pages/layer/info"); 
var animationEnd = require("../animation/animationEnd"); // 
var calendar = require("../util/calendar"); // 日历函数

var wraprender = require("./select-date.ejs"); // 日历模版
var daterender = require("./calendar.ejs"); // 日历模版
var backRender = require("./backhome.ejs");

module.exports = function(opts) {
    var nodeList = null; // 存储所有关键节点
	var that = base();
    var data = null;
	var m_now = null;	
	var m_today = null ;
	var curGid = null;
    var oldItem = null;
	var m_status =null;
	var m_msg =null;
	//-------------事件响应声明---------------
    var evtFuncs = {
			submitCalendar:function(){			
				   var selectday = nodeList.selectday;
				   var timeStr = selectday.value,timeArr;
				   if(timeStr==''){showMessage("请选择出游日期");return;}
				   var sbdata = {"ocid":data.ocid,"price":timeStr.replace(/(\d+-\d+-\d+)-([\d.]+)-\d+-\d+/,"$2"),"goods_id":timeStr.replace(/(\d+-\d+-\d+)-([\d.]+)-(\d+)-\d+/,"$3"),"date":timeStr.replace(/(\d+-\d+-\d+)-([\d.]+)-\d+-\d+/,"$1"),"week":timeStr.replace(/(\d+-\d+-\d+)-([\d.]+)-\d+-(\d+)/,"$3"),"dateType":"1","tid":data.tid};
				    if(data.tcid){
						sbdata.tcid = data.tcid;
				    }
				   var params = extend(JSON.parse(selectday.dataset.json),sbdata);		
		 
				   custFuncs.sendData(params);	
			},
			switchMoth:function(evt){
				var target = closest(evt.target,".switchMoth",true), timeStr = target.getAttribute("data-time"),timeArr,flag;
				var elemdata = nodeList.selectday.dataset.json;
				if(target.classList.contains("disabled")){
					return ;
				}
				flag = target.classList.contains("prev") ? "prev" : "next";
				timeArr = timeStr.split("-");
				custFuncs.getCalendar({
						"year":parseInt(timeArr[0]),
						"month":parseInt(timeArr[1]),
						"gid":curGid,
						"elemjson":elemdata,
						"callback":null,
						"flag":flag
					});
			},
			allowedTap:function(evt){
				  var target = closest(evt.target,".day",true),timeStr;                   
						oldItem && oldItem.classList.remove("active");
						target.classList.add("active");
						timeStr = target.getAttribute("data-time");
						nodeList.selectday && (nodeList.selectday.value=timeStr);
						localStorage.removeItem("dateTime")
						localStorage.setItem("dateTime",timeStr);
						oldItem = target;
			   },
			   show:function(strdata){
				   var elemdata = JSON.parse(strdata);
					custFuncs.getCalendar({
						"year":new Date().getFullYear(),
						"month":new Date().getMonth(),
						"gid":elemdata.id,
						"elemjson":strdata,
						"callback":function(){
							nodeList.datepicker.style.display = "block";
							nodeList.mask.style.opacity ="1";
							nodeList.datebox.classList.add("slidein")
							animationEnd(nodeList.datebox, "AnimationEnd", function () {
								document.body.classList.add('modal-open');
								nodeList.datebox.classList.remove("slidein");
							}, false);	
						}
					});
			   },
			   hide:function(){
						nodeList.mask.style.opacity ="0";
						nodeList.datebox.classList.add("slideout")
						animationEnd(nodeList.datebox, "AnimationEnd", function () {
							document.body.classList.remove('modal-open');
							nodeList.datebox.classList.remove("slideout")
							nodeList.datepicker.style.display ="none";
							nodeList.datebox.innerHTML = "";
						}, false);	
			   },
				buyItem:function(e){
					var target=closest(e.target,".buyitem",true),gid=target.dataset.id,monthstr = target.dataset.month;
					if(target.classList.contains("sellout")){
						return ;
					}
					if(target.classList.contains("selling")){
						Alert(target.dataset.selling.replace(/\d+-(\d+)-(\d+).*/,"商品将在$1月$2日开售哦~"));
						return ;
					}				
					var elemdata = JSON.stringify(target.dataset);
					
					evtFuncs.show.call(null,elemdata);
				},
			switchdate:function(e){
				var target=closest(e.target,".m-travel-date",true),gid=target.dataset.id,monthstr = target.dataset.month;
				var elemdata = JSON.stringify(target.dataset);				
				evtFuncs.show.call(null,elemdata);
			}
	};
    //-------------子模块实例化---------------
    var initMod = function() {
		m_now = new Date();
		m_today = m_now.getFullYear()+"-"+(m_now.getMonth()+1)+"-"+ new Date().getDate();
	};
    //-------------绑定事件------------------
    var bindEvents = function() {
		   if(nodeList.switchdate){
			   touch.on(nodeList.switchdate,"tap",evtFuncs.switchdate);
		   }
		   if(nodeList.buylist){
			   touch.on(nodeList.buylist,"tap",".buyitem",evtFuncs.buyItem);
		   }			
			touch.on(nodeList.datebox,"tap",".switchMoth",evtFuncs.switchMoth); 
			touch.on(nodeList.datebox,"tap",".allowed",evtFuncs.allowedTap); 
			touch.on(nodeList.datebox,"tap",".submit",evtFuncs.submitCalendar); 
			touch.on(nodeList.datebox,"tap",".close-wrap",evtFuncs.hide);
			touch.on(nodeList.mask,"tap",evtFuncs.hide);
	};
    //-------------自定义函数----------------
    var custFuncs = {
				comparemonth:function(a,b){
					var arr = a.split("-");
					var brr = b.split("-");
					var bool = (new Date(arr[0],arr[1]).getTime() - new Date(brr[0],brr[1]).getTime())>=0;
					return bool;
				},
				 renderCalendar:function(result){
					var  mothdays = calendar(result.year, result.month).getView();
					
					var newMothDays = [];
					var priceIndex = 0;
					var prevDays = mothdays.prevDays;
					var lastDaynum = prevDays+mothdays.mDays;

					mothdays.view.forEach(function(item,index){
						if(index+1<=prevDays){
							item.prefixM = "old";
						}else if(index+1>lastDaynum){
							 item.prefixM = "new";
						}else{
							 result.pricedata[priceIndex] && (item.price = result.pricedata[priceIndex].price,item.id =result.id,item.isok = result.pricedata[priceIndex].isok,item.prefixM = "day");                   
							  priceIndex++;
						}

						newMothDays.push(item); 
					});
					var calendarTemp = daterender({
						"preMonthable" : custFuncs.comparemonth(nodeList.selectday.dataset.oldmoth,result.year+"-"+result.month),
						"dateList":newMothDays,
						"prevM":mothdays.prevM.y+"-"+mothdays.prevM.m,
						"nexM":mothdays.nextM.y+"-"+mothdays.nextM.m,
						"curM":result.year+"-"+result.month,
						"switchMoth":result.year+"年"+result.month+"月",
						"trarr":newMothDays.length==35 ? [6,13,20,27] : [6,13,20,27,34]
					});
					nodeList.datebox.innerHTML =  calendarTemp;
					nodeList.selectday.dataset.json = result.elemjson;
				 },
				getCalendar:function(options){
					if(that.isLock()) {
						return;
					}
					that.lock();
					ajax({
						url: "/index.php?r=goods/detail&selectYear="+options.year+"&selectMonth="+options.month+"&goods_id="+options.gid+"&ocid="+data.ocid+(options.flag ? "&flag="+options.flag : ""),
						timeout: 30000, // 缺少值3秒,
						data: { selectYear: options.year,selectMonth:options.month}, // 仅method=post时生效，如果传入json对象会被转换成queryString，如果传入字符串则会原样发送
						method: "post", // 默认是get
						onSuccess: function(result) {
								that.unLock();	
								var status = result.status;
								if(status==0){									
									showMessage(result.msg);		
								}else{
									if(typeof(opts)!="object" && opts!=null){	
										if(opts.scheduled){
											var buystart = result.buyRules.buyStartDay.replace(/(\d+)-(\d+)-(\d+)[\s\d:]+/g,"$1/$2/$3");
											if(result.buyRules.isSale==1 && Date.parse(buystart)>new Date().getTime()){
												document.body.classList.add('bg-backhome');
												 document.body.insertAdjacentHTML('AfterBegin', backRender({"message":result.buyRules.buyStartDay.replace(/(\d+)-(\d+)-(\d+)[\s\d:]+/g,"$2月$3")+"日开售，去微商城看看吧","homelink":"/index.php?r=index/index"}));		
												return;										 
											}else if(result.buyRules.isSale==0){
												// alert("商品已售罄");
												document.body.classList.add('bg-backhome');
												document.body.insertAdjacentHTML('AfterBegin', backRender({"message":"商品已售罄，去微信商城看看吧","homelink":"/index.php?r=index/index"}));
												return;	
											}	
										}
									}
									switch(result.dateType){	
										case 1 :	
						                    curGid = options.gid;
											m_status = result.status;
											var sym = result.selectYearMonth.split("-");
											if(!this.flag){
												nodeList.selectday.dataset.oldmoth = result.selectYearMonth;
											}
											m_msg = "";
											var params = extend({"date":m_today},result.buyRules,result.effect,JSON.parse(this.elemjson));
											custFuncs.renderCalendar({
												"newMonth":sym,
												"year":sym[0],
												"month":sym[1],
												"id":options.gid,
												"elemjson":JSON.stringify(params),
												"pricedata":result.price,
												"dateType":result.dateType
											});
											this.callback && this.callback();
											break;
										case 2 :
										case 3 :   	
										  var params = extend({"ocid":data.ocid,"price":result.price,"dateType":result.dateType,"goods_id":this.gid,"date":m_today,"tid":data.tid},result.buyRules,result.effect,JSON.parse(this.elemjson));										
										   if(data.tcid){params.tcid=data.tcid;}
										   custFuncs.sendData(params);	
											break;
										default:
												showMessage(result.msg);
									}
								}
						}.bind(options),
						onError: function(xmlHttp) {
							that.unLock();
						},
                        onTimeout: function(xmlHttp) {alert("超时触发"); }, // 超时触发
                        onAbort: function() { alert("网络中断时触发");} // 网络中断时触发
					});
				},
				sendData:function(result) {
                    if(result.price == undefined){
						showMessage("请选择出游日期");
						return;
					}
					if(typeof(result.goods_id)=="undefined"){
						showMessage("无效的商品ID");
						return;
					}
					var name,
						form = document.createElement("form"),
						node = document.createElement("input");
                         if((typeof(opts)=="object") && opts!=null && opts.formAction){	
                             form.action = opts.formAction;
                         }else{
                         	form.action = "/index.php?r=scheduled/scheduled&ocid="+data.ocid+"&goods_id="+result.goods_id;
                         }
						
						form.method = "post";
						for(name in result) {
							if(typeof(result[name]!="undefined")){
								node.name  = name;
								node.value = (result[name]||"").toString();
								form.appendChild(node.cloneNode());
							}
						}
						// 表单元素需要添加到主文档中.
						form.style.display = "none";
						document.body.appendChild(form);
						form.submit();
						
				}
	};
    //-------------一切从这开始--------------
    var init = function(_data) {
        data = _data;
        if(!document.getElementById('selectDate')){
			document.body.insertAdjacentHTML('beforeend', wraprender({"year":json.data,"month":json.data,"ocid":data.ocid}));
		}
        // 找到所有带有node-name的节点
        nodeList = parseModule(document.body);
        // 子模块实例化
        initMod();

        // 绑定事件
        bindEvents();

    }

    //---------------暴露API----------------
    that.init = init;
    that.getCalendar = custFuncs.getCalendar;

    return that;
};